package one.stand.advice;

/**
 * @author: QIK
 * @CreateDate: 2019/4/18 22:40
 */

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileUploadBase;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice(annotations = RestController.class)
@ResponseBody
@Slf4j
public class ExceptionHandlerAdvice {

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Map<String, String> exceptionHandle(HttpServletRequest request, Exception e) {
        log.error("异常路径:" + request.getRequestURI());
        log.error("系统异常:" + JSON.toJSONString(request.getParameterMap()),e);
        Map<String,String> result=new HashMap<>(3);
        result.put("code","500");
        result.put("message","网络错误");
        result.put("success","true");
        return result;
    }

    /**
     * 全局异常捕捉处理
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = FileUploadBase.SizeLimitExceededException.class)
    public  Map<String, String> sizeLimitExceededException(HttpServletRequest request,FileUploadBase.SizeLimitExceededException e) {
        log.error("异常路径:" + request.getRequestURI());
        log.error("系统异常:" + JSON.toJSONString(request.getParameterMap()),e);
        Map<String,String> result=new HashMap<>(3);
        result.put("code","206");
        result.put("message","文件过大");
        result.put("success","true");
        return result;
    }

    @ResponseBody
    @ExceptionHandler(value = HttpMediaTypeNotSupportedException.class)
    public  Map<String, String> httpMediaTypeNotSupportedException(HttpServletRequest request,HttpMediaTypeNotSupportedException e) {
        log.info(e.getMessage(),e);
        Map<String,String> result=new HashMap<>(3);
        result.put("code","207");
        result.put("message","文件为空");
        result.put("success","true");
        return result;
    }


}
